package com.jinyi.wwdeng.autodialer.utils

import android.content.Context
import android.provider.CallLog
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.json.JSONArray
import org.json.JSONObject


/**
 * 读取通话记录
 * <uses-permission android:name="android.permission.READ_CALL_LOG" />
 *
 * path: /v2/callRecord
 * param: callLogListGzip
 */
object CallLogUtil {

    /**
     * 读取通话记录
     */
    suspend fun read(context: Context,number: String): String = withContext(Dispatchers.IO) {
        val callsLog = JSONArray()

        val mColumns = arrayOf(
            CallLog.Calls.IS_READ,
            CallLog.Calls.NEW,
            CallLog.Calls.CACHED_NUMBER_TYPE,
            CallLog.Calls.CACHED_NAME,
            CallLog.Calls.NUMBER,
            CallLog.Calls.DATE,
            CallLog.Calls.DURATION,
            CallLog.Calls.TYPE
        )

        // 查询条件：按号码过滤
        val selection = "${CallLog.Calls.NUMBER} = ?"
        val selectionArgs = arrayOf(number)

        // 排序：按时间降序
        val sortOrder = "${CallLog.Calls.DATE} DESC"

        val cursor = context.contentResolver.query(CallLog.Calls.CONTENT_URI, mColumns, selection, selectionArgs, sortOrder)
        cursor?.use { cur ->
            try {
                val isReadIndex = cur.getColumnIndex(CallLog.Calls.IS_READ)//是否已读（0/1）
                val isNewIndex = cur.getColumnIndex(CallLog.Calls.NEW)//是否为新通话（0/1）
                val nameIndex = cur.getColumnIndex(CallLog.Calls.CACHED_NAME)//联系人姓名（如果有）
                val dateIndex = cur.getColumnIndex(CallLog.Calls.DATE)//通话时间（Unix 时间戳，毫秒）
                val numberIndex = cur.getColumnIndex(CallLog.Calls.NUMBER)//电话号码
                val durationIndex = cur.getColumnIndex(CallLog.Calls.DURATION)//通话时长（秒）
                val typeIndex = cur.getColumnIndex(CallLog.Calls.TYPE)//通话类型

                while (cur.moveToNext()) {
                    val isRead = cur.getInt(isReadIndex).toString()
                    val isNew = cur.getInt(isNewIndex).toString()
                    val name = cur.getString(nameIndex) ?: ""
                    val dateLong = cur.getLong(dateIndex).toString()
                    val mobile = cur.getString(numberIndex) ?: ""
                    val duration = cur.getLong(durationIndex).toString()
                    val typeInt = cur.getInt(typeIndex)
                    val type = typeInt.toString()
                    val typeDes = formatType(typeInt)
                    val readDes = if (isRead == "0") "YES" else "NO"

                    callsLog.put(JSONObject().apply {
                        put("isRead",readDes)
                        put("isNew",isNew)
                        put("name",name)
                        put("dateLong",dateLong)
                        put("mobile",mobile)
                        put("duration",duration)
                        put("type",type)
                        put("typeDes",typeDes)
                    })
                }
            } catch (e: Exception) {
                //
            }
        }
        //只上报最新一条记录
        if (callsLog.length() > 0){
            callsLog.optJSONObject(0).toString()
        } else {
            ""
        }
    }

    private fun formatType(type: Int): String {
        return when (type) {
            CallLog.Calls.INCOMING_TYPE -> "INCOMING_TYPE"
            CallLog.Calls.OUTGOING_TYPE -> "OUTGOING_TYPE"
            CallLog.Calls.MISSED_TYPE -> "MISSED_TYPE"
            CallLog.Calls.VOICEMAIL_TYPE -> "VOICEMAIL_TYPE"
            CallLog.Calls.REJECTED_TYPE -> "REJECTED_TYPE"
            CallLog.Calls.BLOCKED_TYPE -> "BLOCKED_TYPE"
            CallLog.Calls.ANSWERED_EXTERNALLY_TYPE -> "ANSWERED_EXTERNALLY_TYPE"
            else -> ""
        }
    }
}